package com.icart.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.icart.WxTemplate.TemplateData;
import com.icart.WxTemplate.WxTemplate;
import com.icart.comm.AjaxRspResult;
import com.icart.context.HttpUserContext;
import com.icart.context.provider.UserContextProvider;
import com.icart.context.storage.ContextStorage;
import com.icart.context.storage.SessionContextStorageImpl;
import com.icart.entities.CuCustinfoEntity;
import com.icart.repositories.CustinfoRepository;
import com.icart.util.Tools;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


@Controller
public  class HomeController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpSession session;
    @Autowired
    private RestTemplate template;
    @Autowired
    private CustinfoRepository custinfoRepository;

    protected Logger logger = LoggerFactory.getLogger(HomeController.class);
    /*首页*/
    @RequestMapping("indexs")
    public String indexs(Model model,HttpServletRequest request) {
        if(request.getSession().getAttribute("openid")==null){
            String openid=request.getParameter("openid");
            request.getSession().setAttribute("openid",openid);
            CuCustinfoEntity cuCustinfo=custinfoRepository.loginfindopenid(openid);
            if(cuCustinfo!=null){
            /*设置在session里面*/
                HttpUserContext context= UserContextProvider.create(cuCustinfo.getCustid(),cuCustinfo.getCustname());
                ContextStorage storage=new SessionContextStorageImpl(request);
                storage.save("loginuser",context);
            }
        }
        return "index";
    }

    @RequestMapping(value = "/savelocation",method = RequestMethod.GET)
    @ResponseBody
    public AjaxRspResult savelocation(Model model) {
        AjaxRspResult arr = new AjaxRspResult();
        if(Tools.notEmpty(request.getParameter("lon"))) {
            String lat = request.getParameter("lat");
            String lon = request.getParameter("lon");
            session.setAttribute("lat",lat);
            session.setAttribute("lon",lon);
        }
        if(Tools.notEmpty(request.getParameter("address"))) {
            String address = request.getParameter("address");
            String adcode = request.getParameter("adcode");
            session.setAttribute("address", address);
            session.setAttribute("adcode", adcode);
        }
            arr.setResult("success");
            return arr;

    }

    @RequestMapping("/logingetmessage")
    @ResponseBody
    public String logingetmessage(@RequestParam(name = "mobile",required = false) String mobile,
                       @RequestParam(name = "code",required = false) String code) {
        System.out.println("11111="+mobile);
        System.out.println("11111="+code);
        String messagenum=null;
        String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）

        try {
            // 根据不同短信供应商实现发短信
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            String accessKeyId ="LTAI3XPE5gPmpipW";//你的accessKeyId,参考本文档步骤2
            String accessKeySecret = "Qe5k6YVrXw5GZuoZ63eMD7pyF5LpEr";//你的accessKeySecret，参考本文档步骤2
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            try {
                DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            } catch (ClientException e) {
                e.printStackTrace();
            }
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(mobile);//多个用,分割
            request.setSignName("养护通汽车服务");
            request.setTemplateCode("SMS_126610256");//控制台设置的模板
            request.setTemplateParam("{\"code\":\"" + code + "\"}");//短信模板中填充的内容
            //请求失败这里会抛ClientException异常
            SendSmsResponse sendSmsResponse = null;
            try {
                sendSmsResponse = acsClient.getAcsResponse(request);
            } catch (ClientException e) {
                e.printStackTrace();
            }
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                System.out.println("验证码为="+sendSmsResponse.getCode());
                messagenum="success";
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        return "success";
    }

    @RequestMapping("/welcome")
    @ResponseBody
    public String welcome(Model model) {
        return "wechat system";
    }

    public static void gettoken(Model model,RestTemplate template,String tokenurl,HttpServletRequest request){
        WxUtilController wxUtilController=new WxUtilController();
        String token=wxUtilController.getToken(template,request);/*师兄最外一层token*/
        String accesstoken=wxUtilController.getAccesstoken(template,request);/*师兄token里面封装了微信的accesstoken*/
        model.addAttribute("accesstoken",accesstoken);
        /*微信前台要用的config信息*/
        String url3=tokenurl+token;
        String content3= template.getForEntity(url3,String.class).getBody();
        System.out.println("content3="+content3);
        String appId=JSON.parseObject(content3).getJSONObject("result").getJSONObject("signbag").getString("appId");
        String timestamp=JSON.parseObject(content3).getJSONObject("result").getJSONObject("signbag").getString("timestamp");
        String nonceStr=JSON.parseObject(content3).getJSONObject("result").getJSONObject("signbag").getString("nonceStr");
        String signature=JSON.parseObject(content3).getJSONObject("result").getJSONObject("signbag").getString("signature");
        model.addAttribute("appId",appId);
        model.addAttribute("timestamp",timestamp);
        model.addAttribute("nonceStr",nonceStr);
        model.addAttribute("signature",signature);
    }

    public static String getPic( String mediaId,RestTemplate template,HttpServletRequest request) {
        WxUtilController wxUtilController=new WxUtilController();
        String accesstoken=wxUtilController.getAccesstoken(template,request);
        String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN",accesstoken ).replace("MEDIA_ID", mediaId);
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.IMAGE_JPEG,MediaType.IMAGE_PNG));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<byte[]> bs=template.exchange(requestUrl, HttpMethod.GET, entity,byte[].class);//下载图片
        System.out.println(bs.getStatusCode());
        String base64 = java.util.Base64.getEncoder().encodeToString(bs.getBody());
        return base64;
    }

    public static void gettoken2(Model model,RestTemplate template,String tokenurl,HttpServletRequest request){
        WxUtilController wxUtilController=new WxUtilController();
        String token=wxUtilController.getToken2(template,request);/*师兄最外一层token*/
        String accesstoken=wxUtilController.getAccesstoken2(template,request);/*师兄token里面封装了微信的accesstoken*/
        model.addAttribute("accesstoken",accesstoken);
        /*微信前台要用的config信息*/
        String url3=tokenurl+token;
        String content3= template.getForEntity(url3,String.class).getBody();
        System.out.println("content3="+content3);
        String appId=JSON.parseObject(content3).getJSONObject("result").getJSONObject("signbag").getString("appId");
        String timestamp=JSON.parseObject(content3).getJSONObject("result").getJSONObject("signbag").getString("timestamp");
        String nonceStr=JSON.parseObject(content3).getJSONObject("result").getJSONObject("signbag").getString("nonceStr");
        String signature=JSON.parseObject(content3).getJSONObject("result").getJSONObject("signbag").getString("signature");
        model.addAttribute("appId",appId);
        model.addAttribute("timestamp",timestamp);
        model.addAttribute("nonceStr",nonceStr);
        model.addAttribute("signature",signature);
    }

    public static String getPic2( String mediaId,RestTemplate template,HttpServletRequest request) {
        WxUtilController wxUtilController=new WxUtilController();
        String accesstoken=wxUtilController.getAccesstoken2(template,request);
        String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN",accesstoken ).replace("MEDIA_ID", mediaId);
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.IMAGE_JPEG,MediaType.IMAGE_PNG));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<byte[]> bs=template.exchange(requestUrl, HttpMethod.GET, entity,byte[].class);//下载图片
        System.out.println(bs.getStatusCode());
        String base64 = java.util.Base64.getEncoder().encodeToString(bs.getBody());
        return base64;
    }

    /*获取微信个人的openid*/
    @RequestMapping("/index")
    public String getOpenId() {
        /* 师兄接口的token*/
        WxUtilController wxUtilController=new WxUtilController();
        String result=wxUtilController.getToken(template,request);
        String requestUrl = "http://api.wechat.ikartek.com/wechat/oauth?name=Name&redirectUrl=RedirectUrl&token=Token";
        requestUrl = requestUrl.replace("Name","gh_3407fa0da217");
        requestUrl = requestUrl.replace("RedirectUrl","http://testwx.ikartek.com/indexs");
        requestUrl = requestUrl.replace("Token",result);
        return "redirect:"+requestUrl;
    }

}